<?php

namespace App\Http\Controllers\Company;

use App\Facades\Style;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyContract;
use App\Models\Company\MyOrder;
use App\Models\Company\VipPackage;
use App\Models\Company\CompanyUser;
use App\Models\Company\CrmService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use DB,Response;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class MyOrderController extends CommonController{
    /**
     * 我的VIP套餐
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function index(){
        $userInfo = auth()->guard('company')->user();
        //企业基本信息
        $companyBasic=CompanyBasic::where('uid',$userInfo->uid)->orderBy('updatetime', 'desc')->first();

        if ($userInfo->viptime > date('Y-m-d H:i:s')) {//会员优先使用会员积分
            $integral = $userInfo->vip_integral;
            $resume_number = $userInfo->vip_resume_number;
            $post_number = $userInfo->vip_post_number;
            if ($integral <= 0) {
                $integral = $userInfo->integral;
            }
            if ($resume_number <= 0) {
                $resume_number = $userInfo->resume_number;
            }
            $user_type = 'vip';
            $vipday = $this->timeDiff($userInfo->viptime)[0].$this->timeDiff($userInfo->viptime)[1];
        } else {
            $integral = $userInfo->integral;
            $resume_number = $userInfo->resume_number;
            $post_number = 0;
            $user_type = 'general';
            $vipday = 0;
        }
        $vip = array(
            'day' => $vipday,
            'integral' => $integral,
            'resume_number' => $resume_number,
            'post_number' => $post_number,
            'user_type' => $user_type
        );

        //ＶＩＰ套餐信息
        $VipPackage = VipPackage::where('stats',0)->orderBy('updated_at','desc')->get();
        foreach($VipPackage as $v){
            //为每个套餐生成一个token 30位码 16字母数据+14位时间
            $v->token = str_random(16);
        }

        return Style::view('company.myOrder',compact('companyBasic','vip','VipPackage'));
    }

    /**
     * 我的VIP订单
     * @param Request $request
     * @return mixed
     */
    public function myOrderList(Request $request){

        $vip_id = intval($request->vip_id);
        $token = $request->token;
        $user = Auth::guard('company')->user();
        $stats = $request->stats;
        $input = $request->only('vip_id','vip_name','token','money');
        $input['uid'] = $user->uid;
        $input['created_at'] = date("Y-m-d H:i:s",time());
        $input['updated_at'] = date("Y-m-d H:i:s",time());

        try{
            if($vip_id > 0){
                //创建一份定单,用token 验证是否已生成定单，避免重复生成
                if(!MyOrder::where('token',$token)->count()){
                    $newOrderId = MyOrder::insertGetId($input);
                    //弹出框=》套餐信息
                    if($VipPackage = VipPackage::where('id',$vip_id)->first()){
                        $VipPackage->orderId = $newOrderId;

                        //客服信息
                        $CrmUser = CompanyUser::select("uid","crm_uid")
                            ->with(['withService'=>function($query){
                                $query->select('uid','worker_name','phone');
                            }])
                            ->where('uid',Auth::guard('company')->user()->uid)
                            ->first();
                    }

                }
            }
        }catch (\PDOException $e){
            abort(503);
        }

        //定单信息与支付方式
        $MyOrder = MyOrder::with(['myOrderWithCollOptions' => function($query){
                $query->select('opt_id','opt_name')
                ->where('sign' , 'pay');
            }])
            ->where(function($querey) use($stats){
                if($stats != ''){
                    $querey->where('stats',$stats);
                }
            })
            ->where('uid',$user->uid)
            ->orderBy('created_at','desc')->paginate(10);

        if($MyOrder){
            foreach($MyOrder as $v){
                switch($v->stats){
                    case 0:
                        $v->payStats = '未支付';
                        break;
                    case 1:
                        $v->payStats = '已取消';
                        break;
                    case 2:
                        $v->payStats = '已支付';
                        break;
                }
            }
        }

        return Style::view('company.myOrderList',compact('MyOrder','newOrderId','VipPackage','CrmUser'));
    }

    /**
     * 我的VIP订单支付页面
     * @param Request $request
     * @return mixed
     */
    public function myOrderPay(Request $request){
        $id = intval($request->id);

        $MyOrder = MyOrder::select('id','vip_id','stats','money')->where('id',$id)->with('myOrderWithVipPackage')->first();
        if($MyOrder){
            //客服信息
            $CrmUser = CompanyUser::select("uid","crm_uid")
                ->with(['withService'=>function($query){
                    $query->select('uid','worker_name','phone');
                }])
                ->where('uid',Auth::guard('company')->user()->uid)
                ->first();

            return Style::view('company.myOrderPay',compact('MyOrder','CrmUser'));
        }else{
            abort(404);
        }
    }

    /**
     * 我的VIP订单付款
     * @param $orderId
     * @param $orderMoney
     * @return \Illuminate\Http\JsonResponse
     */
    public function myOrderToPay(Request $request){
        $orderId = intval($request->orderId);
        $payType = intval($request->payType);

        //这里返回支付宝或微信 充值情况.
        $MyOrder = MyOrder::where('id',$orderId)->first();

        switch($payType){
            case 15://支付宝
                return $this->alipay($MyOrder);
                break;
            case 16://微信
                return $this->mpWeiXinPay($MyOrder);
                break;
        }
    }

    /**
     * 支付宝定单生成提交页面
     */
    private function alipay($MyOrder){
        require_once(app_path("Vendor/Alipay/alipay.config.php"));
        require_once(app_path("Vendor/Alipay/lib/alipay_submit.class.php"));

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = 'Order-'.$MyOrder->id.'-'.date('YmdHis');

        //订单名称，必填
        $subject = $MyOrder->vip_name;

        //付款金额，必填
        $total_fee =$MyOrder->money;//

        //商品描述，可空
        $body = $MyOrder->vip_name.'套餐';

        //构造要请求的参数数组，无需改动 $alipay_config 如果编辑器显示红线提示错误，没有关系
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type"	=> $alipay_config['payment_type'],
            "notify_url"	=> $alipay_config['notify_url'],
            "return_url"	=> $alipay_config['return_url'],

            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"

        );

        //建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        return $html_text;
    }

    /**
     * 支付宝通知页面
     */
    public function alipayNotice(Request $request){
        require_once(app_path("Vendor/Alipay/alipay.config.php"));
        require_once(app_path("Vendor/Alipay/lib/alipay_notify.class.php"));
        require_once(app_path("Vendor/Alipay/lib/alipay_core.function.php"));
        require_once(app_path("Vendor/Alipay/lib/alipay_rsa.function.php"));
        //计算得出通知验证结果   $alipay_config 编辑器显示红线没关系
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify($request);

        if($verify_result){
            switch($request->trade_status){
                case "WAIT_BUYER_PAY"://交易创建，等待买家付款。

                    $str = $request->body."购买成功，但您还未付款";
                    return redirect(route("myOrder.list"))->with('orderErr',$str);
                    break;

                case "TRADE_CLOSED"://在指定时间段内未支付时关闭的交易；

                    $str = $request->body."购买失败，交易失效，请重新付款";
                    return redirect(route("myOrder.list"))->with('orderErr',$str);
                    break;

                case "TRADE_SUCCESS"://交易成功，且可对该交易做操作，如：多级分润、退款等。

                    $out_trade_no = explode('-',$request->out_trade_no);//返回ID格式 Order-82-20170328143320
                    $orderId = intval($out_trade_no[1]);

                    //更新定单为支付成功
                    try{
                        $MyOrder = MyOrder::where('id',$orderId)->where('money',$request->total_fee)->first();
                        if($MyOrder){
                            if($MyOrder->stats == 2){ //2表示已购买
                                $str = '';
                                return redirect(route("myOrder.list"))->with('orderErr',$str);
                            }else{
                                $MyOrder->stats = 2;//更新订单为购买
                                $MyOrder->pay_type = 15;//支付宝购买
                                $MyOrder->save();

                                if($this->createContract($orderId,15)){//15代表支付宝,创建合同更新vip信息
                                    echo "success";
                                    $str = $request->body."购买成功";
                                    return redirect(route("myOrder.list"))->with('orderSuccess',$str);
                                }else{
                                    // 一般合创建失败，多是viptime 时间问题，超过了目前最大时间戳 2038-01-18 16:16:51
                                    $str = $request->body."购买失败，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）";
                                    return redirect(route("myOrder.list"))->with('orderErr',$str);
                                }
                            }
                        }else{
                            $str = $request->body."购买失败，订单异常，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）";
                            return redirect(route("myOrder.list"))->with('orderErr',$str);
                        }

                    }catch (\PDOException $e){
                        $str = $request->body."购买失败，订单异常，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）";
                        return redirect(route("myOrder.list"))->with('orderErr',$str);
                    }
                    break;

                case "TRADE_PENDING"://等待卖家收款（买家付款后，如果卖家账号被冻结）。

                    $str = $request->body."购买成功，但支付宝未到账，请联系客服操作（帐户中心可查看您的客服代表）";
                    return redirect(route("myOrder.list"))->with('orderErr',$str);
                    break;

                case "TRADE_FINISHED"://交易成功且结束，即不可再做任何操作

                    $str = $request->body."已购买";
                    return redirect(route("myOrder.list"))->with('orderSuccess',$str);
                    break;

                case "REFUND_SUCCESS"://交易成功且结束，即不可再做任何操作
                    break;
            }
        }else{//参数与配置config文件不匹配
            $str = $request->body."交易失效,参数不匹配";
            return redirect(route("myOrder.list"))->with('orderErr',$str);
        }

    }

    /**
     * 支付宝异步通知页面
     * 如果用户
     */
    public function alipayAjax(Request $request){

        \Illuminate\Support\Facades\Log::info('aliPay->pid'.$request->out_trade_no.'-->'.$request->total_fee);

        switch($request->trade_status){
            case "TRADE_SUCCESS"://交易成功，且可对该交易做操作，如：多级分润、退款等。
                $out_trade_no = explode('-',$request->out_trade_no);//返回ID格式 Order-82-20170328143320
                $orderId = intval($out_trade_no[1]);

                //更新定单为支付成功
                try{
                    $MyOrder = MyOrder::where('id',$orderId)->where('money',$request->total_fee)->first();
                    if($MyOrder){
                        if($MyOrder->stats == 2){ //2表示已购买 购买失败，请勿重复提交订单
                            echo "fail";
                        }else{
                            $MyOrder->stats = 2;//更新订单为购买
                            $MyOrder->pay_type = 15;//支付宝购买
                            $MyOrder->save();

                            if($this->createContract($orderId,15)){//15代表支付宝,创建合同更新vip信息
                                echo "success";
                            }else{
                                //合同创建或vip 信息更新失败,不处理，让支付宝再次发送数据
                                // 一般合创建失败，多是viptime 时间问题，超过了目前最大时间戳 2038-01-18 16:16:51
                            }
                        }
                    }else{//购买失败，订单异常，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）
                        echo "fail";
                    }

                }catch (\PDOException $e){//购买失败，订单异常，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）
                    echo "fail";
                }

                break;
            case "TRADE_FINISHED"://交易成功且结束，即不可再做任何操作
                break;
        }

    }

    /**
     * 微信支付二维码组装地址
     * @param Request $request
     */
    public function mpWeiXinPay($MyOrder){

        require_once(app_path("Vendor/MpWeiXin/lib/WxPay.Api.php"));
        require_once(app_path("Vendor/MpWeiXin/api/WxPay.NativePay.php"));
        require_once(app_path("Vendor/MpWeiXin/api/log.php"));
        require_once(app_path("Vendor/MpWeiXin/api/phpqrcode/phpqrcode.php"));

        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($MyOrder->vip_name);//支付标题
        $input->SetAttach($MyOrder->id);//附加消息 商家数据包，原样返回
        $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));//商户订单号
        $input->SetTotal_fee($MyOrder->money * 100);//订单总金额，单位为分
        $input->SetTime_start(date("YmdHis"));//定单提交时间
        $input->SetTime_expire(date("YmdHis", time() + 600));//失效时间
        $input->SetGoods_tag("hr666");//标签
        $input->SetNotify_url(route("myOrder.mpWeiXinNotice"));//微信通知页面
        $input->SetTrade_type("NATIVE");//交易类型  原生支付
        $input->SetProduct_id($MyOrder->id);
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];

        $q = QrCode::format('png')->size(350)->merge(('/public/default/images/logo/wexin_pay.png'),.15)->generate($url2);
        return response($q, 350, [
            'Content-Type' => 'image/png',
        ]);
    }

    /**
     * 这里采用的是微信第二种支付方式-》统一下单
     * 微信支付回调页面
     * 微信传回xml 格式 用simplexml_load_string 函数转化xml格式，获得对象
     * 这里的所有回调 页面只用于测试，实际微信支付后，并无任何动作，只是更新定单为2，创建合同与更新vip时间
     * 如果出现支付成功，但未创建合同，要客服手动操作
     * @param Request $request
     */
    public function mpWeiXinNotice(){

        require_once(app_path("Vendor/MpWeiXin/lib/WxPay.Api.php"));
        require_once(app_path("Vendor/MpWeiXin/lib/WxPay.Notify.php"));
        require_once(app_path("Vendor/MpWeiXin/api/log.php"));
        require_once(app_path("Vendor/MpWeiXin/api/native_notify.php"));

        $notify = new \NativeNotifyCallBack();//统一下单类
        $postStr = file_get_contents('php://input');

        if( !empty($postStr) ){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);//

            $orderId =intval($postObj->attach); //定单号
            $payStatus =$postObj->result_code; //支付状态

            /**测试数据 单号 149，单价0.01*/
//            $postObj = '{"appid":"wx342b6a6fbc9e8e34","attach":"149","bank_type":"ICBC_DEBIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1454850902","nonce_str":"a6gn291z294oy5j28x39ma3ru42rwymy","openid":"oqEpZwrZGCmYknAisH-G9ouASlDc","out_trade_no":"145485090220170402145645","result_code":"SUCCESS","return_code":"SUCCESS","sign":"74157694798F884459EFAC8BBD946CEE","time_end":"20170402145718","total_fee":"1","trade_type":"NATIVE","transaction_id":"4005922001201704025570848495"}';
//            $postObj = json_decode($postObj);
//            $orderId = 149;
//            $payStatus = 'SUCCESS';
            /**end测试数据 */

            $payResult = $notify->NotifyProcess($postObj,$msg);//native_notify  类文件

            if($payStatus != 'SUCCESS'){//付款失败
                echo "fail";
                //
                //$str = "套餐购买失败，微信付款失败!";
                //return redirect(route("myOrder.list"))->with('orderErr',$str);

            }

            $MyOrder = MyOrder::select('money','stats')->where('id',$orderId)->first();
            if($MyOrder){
                if($MyOrder->stats == 2){
                    echo "fail";
                    //不操作
                    //return redirect(route("myOrder.list"));
                }else{//支付成功

                    if($payResult){

                        if(MyOrder::where('id',$orderId)->update(['stats'=>2,'pay_type'=>16])){
                            if($this->createContract($orderId,16)){//16代表微信支付,创建合同更新vip信息
                                //echo "SUCCESS";
                                $response = Response::make('SUCCESS', 200);
                                $response->header('Content-Type', 'text/xml');
                                return $response;
                                //$str = "购买成功";
                                //return redirect(route("myOrder.list"))->with('orderSuccess',$str);
                            }else{
                                //合同创建或vip 信息更新失败
                                //$str = "合同创建失败，如果微信支付成功，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）";
                                //return redirect(route("myOrder.list"))->with('orderErr',$str);
                            }
                        }

                    }else{//微信通信页面=> 返回状态参数不对（金额或定单状态和定单对不上，或支付失败）
                        //$str = "套餐购买失败，支付信息有误，如果微信支付成功，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）";
                        //return redirect(route("myOrder.list"))->with('orderErr',$str);
                    }

                }
            }else{//查找定单失败
                //$str = "定单不存在，如果微信支付成功，请截图当前页面，并联系客服操作（帐户中心可查看您的客服代表）";
                //return redirect(route("myOrder.list"))->with('orderErr',$str);
            }
            //$notify->Handle(true);//调用WxPayNotify  类
        }
    }


    /**
     * 创建合同,并付款，更新companyUser vip 信息
     * @param $orderId  定单id
     * @param $payType  支付类型 15 支付宝 16 微信
     * 7596天  目前时间最大 2038-01-18 16:16:51
     * @return bool
     */
    private function createContract($orderId,$payType){

        //定单查询 = 套餐类型 + 以前合同信息 + 用户vip 信息
        $MyOrder = MyOrder::with(['myOrderWithVipPackage'=>function($query){
            $query->where('stats',0);
        }])
            ->with(['myOrderWithCompanyUser' => function($query){
                $query->select('uid','viptime','vip_resume_number','vip_integral','vip_post_number','resume_number','integral');
            }])
            ->with(['myOrderWithContract' => function($query){
                $query->select('uid','start_time','end_time')->orderBy('end_time','desc');
            }])
            ->where('id',$orderId)->first();

        if($MyOrder && !empty($MyOrder->myOrderWithVipPackage) && $MyOrder->uid > 0){
            //是提前付款还是正常付款
            if(!empty($MyOrder->myOrderWithCompanyUser)){
                //根据viptime 时间判断是否过期，未过期表示 提前续费，过期代表正常开通
                $MyOrder->refill_type = strtotime($MyOrder->myOrderWithCompanyUser->viptime) >= time() ? '2' : '1';

                //查询套餐会员天数
                $vipDays = $MyOrder->myOrderWithVipPackage->vip_days;

                switch($MyOrder->refill_type){
                    case 1:
                        //正常续费
                        $MyOrder->start_time = date("Y-m-d H:i:s",time());//合同开始时间
                        $MyOrder->end_time = date("Y-m-d H:i:s",strtotime("+$vipDays days",time()));//合同结束时间

                        //企业vip
                        $MyOrder->vipTime = date("Y-m-d H:i:s",strtotime("+$vipDays days",time())); //viptime 时间
                        $MyOrder->vip_resume_number = $MyOrder->myOrderWithVipPackage->vip_resume_number;//会员简历数
                        $MyOrder->vip_integral = $MyOrder->myOrderWithVipPackage->vip_integral;//会员积分
                        $MyOrder->vip_post_number = $MyOrder->myOrderWithVipPackage->vip_post_number;//会员发布职位
                        break;
                    case 2:
                        //提前续费
                        if(!empty($MyOrder->myOrderWithContract)){

                            $preEndTime = $MyOrder->myOrderWithCompanyUser->viptime;//上份合同结束时间
                            $MyOrder->start_time = $preEndTime;
                            $MyOrder->end_time = date("Y-m-d H:i:s",strtotime("+$vipDays days",strtotime($preEndTime)));//合同结束时间
                            $MyOrder->vipTime = date("Y-m-d H:i:s",strtotime("+$vipDays days",strtotime($preEndTime)));//viptime 时间

                            //会员vip 简历数 原来+套餐简历数
                            $vip_resume_number = $MyOrder->myOrderWithCompanyUser->vip_resume_number + $MyOrder->myOrderWithVipPackage->vip_resume_number;
                            $MyOrder->vip_resume_number =$vip_resume_number;

                            //会员vip 积分 原来+套餐积分
                            $vip_integral = $MyOrder->myOrderWithCompanyUser->vip_integral + $MyOrder->myOrderWithVipPackage->vip_integral;
                            $MyOrder->vip_integral = $vip_integral;

                            //会员vip 发布职位  原来+套餐发布职位
                            $vip_post_number = $MyOrder->myOrderWithCompanyUser->vip_post_number + $MyOrder->myOrderWithVipPackage->vip_post_number;
                            $MyOrder->vip_post_number = $vip_post_number;

                        }else{//正常续费
                            $MyOrder->refill_type = 1;//续费方式更改为1 正常续费
                            $MyOrder->start_time = date("Y-m-d H:i:s",time());
                            $MyOrder->end_time = date("Y-m-d H:i:s",strtotime("+$vipDays days",time()));//合同结束时间

                            $MyOrder->vipTime = date("Y-m-d H:i:s",strtotime("+$vipDays days",time())); //viptime 时间
                            $MyOrder->vip_resume_number = $MyOrder->myOrderWithVipPackage->vip_resume_number;//会员vip简历数
                            $MyOrder->vip_integral = $MyOrder->myOrderWithVipPackage->vip_integral;//会员vip积分
                            $MyOrder->vip_post_number = $MyOrder->myOrderWithVipPackage->vip_post_number;//会员vip发布职位
                        }
                        break;
                }

                //合同信息赋值
                $comtractInfo['uid'] = $MyOrder->uid;
                $comtractInfo['category'] = $MyOrder->vip_id;
                $comtractInfo['refill_type'] = $MyOrder->refill_type;
                $comtractInfo['start_time'] = $MyOrder->start_time;
                $comtractInfo['end_time'] = $MyOrder->end_time;
                $comtractInfo['vip_resume_number'] = $MyOrder->myOrderWithVipPackage->vip_resume_number;//会员简历数
                $comtractInfo['vip_integral'] = $MyOrder->myOrderWithVipPackage->vip_integral;//会员积分
                $comtractInfo['vip_post_number'] = $MyOrder->myOrderWithVipPackage->vip_post_number;//会员发布职位
                $comtractInfo['resume_number'] = $MyOrder->myOrderWithVipPackage->resume_number;//非会员简历数
                $comtractInfo['integral'] = $MyOrder->myOrderWithVipPackage->integral;//非会员积分
                $comtractInfo['money'] = $MyOrder->money;//
                $comtractInfo['pay'] = $payType;//支付方式
                $comtractInfo['pay_time'] = date("Y-m-d H:i:s",time());//支付时间
                $comtractInfo['remark'] = '';//备注
                $comtractInfo['admin_uid'] = 0;//自助开通
                $comtractInfo['order_id'] = $orderId;//定单号
                $comtractInfo['created_at'] = date("Y-m-d H:i:s",time());
                $comtractInfo['updated_at'] = date("Y-m-d H:i:s",time());

                //企业vip信息赋值
                $companyUser['viptime'] = $MyOrder->vipTime;
                $companyUser['vip_resume_number'] = $MyOrder->vip_resume_number;
                $companyUser['vip_integral'] = $MyOrder->vip_integral;
                $companyUser['vip_post_number'] = $MyOrder->vip_post_number;

                //非会员简历数 原来+套餐非会员简历数
                $MyOrder->resume_number = $MyOrder->myOrderWithCompanyUser->resume_number + $MyOrder->myOrderWithVipPackage->resume_number;
                $companyUser['resume_number'] = $MyOrder->resume_number;

                //非会员积分 原来+套餐非会员积分
                $MyOrder->integral = $MyOrder->myOrderWithCompanyUser->integral + $MyOrder->myOrderWithVipPackage->integral;
                $companyUser['integral'] = $MyOrder->integral;

                //创建合同 &&  更新企业用户表vip 信息
                $inserId = CompanyContract::insertGetId($comtractInfo);
                try{
                    if(!empty($inserId)){
                        if(CompanyUser::where('uid',$MyOrder->uid)->update($companyUser)){
                            //更新vip 信息
                            return true;
                        }else{
                            //更新用户表失败
                            CompanyContract::destroy($inserId);//删除刚添加的合同
                            return false;
                        }
                    }else{
                        //添加合同失败
                        return false;
                    }
                }catch (\PDOException $e){
                    //数据库异常
                    CompanyContract::destroy($inserId);//删除刚添加的合同
                    //恢复用户原来的vip数据
                    $this->recoveryCompanyUser($MyOrder);
                    return false;
                }

            }else{//找不到相关用户，提示充值失败
                return false;
            }
        }else{//找不到相关定单与套餐，提示充值失败
            return false;
        }
    }

    /**
     * 恢复companyUser 表vip上次的数据
     * @param $MyOrder
     */
    public function recoveryCompanyUser($MyOrder){
        $companyUser = CompanyUser::where('uid',$MyOrder->uid)->first();
        $companyUser->viptime = $MyOrder->myOrderWithCompanyUser->viptime;
        $companyUser->vip_resume_number = $MyOrder->myOrderWithCompanyUser->vip_resume_number;
        $companyUser->vip_integral = $MyOrder->myOrderWithCompanyUser->vip_integral;
        $companyUser->vip_post_number = $MyOrder->myOrderWithCompanyUser->vip_post_number;
        //原来非会员简历数
        $companyUser->resume_number = $MyOrder->myOrderWithCompanyUser->resume_number;
        //原来非会员积分
        $companyUser->integral = $MyOrder->myOrderWithCompanyUser->integral;
        $companyUser->integral = $MyOrder->myOrderWithCompanyUser->integral;
        $companyUser->save();
    }

    /**
     * 取消定单
     */
    public function myOrderCancel(Request $request){
        $id = intval($request->id);
        if($id > 0){
            MyOrder::where('id',$id)->update(['stats' => 1]);
            $status = 0;
            $msg = '定单取消成功';
        }else{
            $status = 1;
            $msg = '操作失败';
        }
        return response()->json(['status'=>$status,'msg' => $msg]);
    }

    /**
     * 功能：计算两个日期相差 年 月 日
     * @param date   $endtime 截止日期日期
     * @return array(int,'单位')
     */
    protected function timeDiff($endtime){
        $starttime = time();
        $endtime = strtotime($endtime);

        $timediff = $endtime - $starttime;
        $days = intval( $timediff / 86400 );
        $remain = $timediff % 86400;
        $hours = intval( $remain / 3600 );
        $remain = $remain % 3600;
        $mins = intval( $remain / 60 );
        $secs = $remain % 60;
        if($days>0) return array($days,'天');
        if($hours>0) return array($hours,'小时');
        if($mins>0) return array($mins,'分种');
        return array($secs,'秒');
    }
}